package com.scpii.api.common.auth.token;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.Assert;

import com.scpii.api.common.auth.ClientAuthentication;
import com.scpii.api.common.exception.InvalidTokenException;
import com.scpii.api.domain.auth.UsersInfoDetails;

public class DefaultTokenService implements TokenService, InitializingBean {

	private TokenStore tokenStore;

	@Override
	public ClientAuthentication loadAuthentication(String accessTokenValue)
			throws AuthenticationException {
		AuthAccessToken accessToken = tokenStore
				.readAccessToken(accessTokenValue);
		if (accessToken == null) {
			throw new InvalidTokenException("Invalid access token: "
					+ accessTokenValue);
		} else if (accessToken.isExpired()) {
			tokenStore.removeAccessToken(accessTokenValue);
			throw new InvalidTokenException("Access token expired: "
					+ accessTokenValue);
		}

		ClientAuthentication result = tokenStore
				.readAuthentication(accessTokenValue);
		return result;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.state(tokenStore != null, "tokenStore is required");
	}

	public void setTokenStore(TokenStore tokenStore) {
		this.tokenStore = tokenStore;
	}

	@Override
	public UsersInfoDetails loadUsersInfoDetails(String accessTokenValue) {
		ClientAuthentication authentication = loadAuthentication(accessTokenValue);
		Object principal = authentication.getPrincipal();
		if (principal instanceof UsersInfoDetails) {
			return (UsersInfoDetails) principal;
		}
		return null;
	}

}
